package cos.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cos.entity.LyricsResponse;
import cos.entity.ParserName;
import cos.entity.Song;

public class DarkLyricsParser implements Parser {

	private final String SITE_URL = "http://www.darklyrics.com/";

	private final Pattern p = Pattern.compile("#");

	@Override
	public LyricsResponse getLyrics(Song song) {
		try {
			String artistURL = generateArtistURL(song);
			String trackUrl = getTrackURL(artistURL, song);
			String trackLyrics = getTrackLyrics(trackUrl);
			if (trackLyrics != null)
				return new LyricsResponse(trackLyrics, ParserName.DARK_LYRICS);
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * Generates artist page url
	 */
	private String generateArtistURL(Song song) {
		/**
		 * construct it in this way: http://www.darklyrics.com/h/hatebreed.html
		 */
		String artLow = song.getArtist().toLowerCase().replaceAll(" ", "");
		String out = SITE_URL + artLow.charAt(0) + "/" + artLow + ".html";
		return out;
	}

	private String getTrackURL(String artistURL, Song song) {
		/**
		 * try to find this expression on a artist page: <a
		 * href="../lyrics/artist/album.html#2">title</a>
		 */
		final Pattern trackURL = Pattern.compile(
				"<a href=\"../(.+)\">" + song.getTitle() + "</a>",
				Pattern.CASE_INSENSITIVE);

		// read the page source
		String page = ParserUtils.readUrlBytes(artistURL);

		// find regexp match
		if (page != null) {
			final Matcher m = trackURL.matcher(page);
			while (m.find()) {
				String temp = m.group(1);
				return (SITE_URL + temp);
			}
		}

		// nothing is finded
		return null;
	}

	private String getTrackLyrics(String albumURL) {
		try {
			String[] data = p.split(albumURL);// albumURL.split("#");
			String page = ParserUtils.readUrlBytes(data[0]);
			int next = 1 + Integer.parseInt(data[1]);
			String reg = "<h3><a name=\"" + data[1]
					+ "\">(.+)</a></h3><br />(.+)<h3><a name=\"" + next;
			page = page.replaceAll('\n' + "", "");
			Pattern p = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(page);
			while (m.find()) {
				String temp = m.group(2);
				temp = temp.replaceAll("<br />", '\n' + "");
				// search by the song number
				return temp;
			}
			return null;
		} catch (Exception e) {
			return null;
		}
	}
}
